"""
安装moviepy前要安装imagemagick 
https://imagemagick.org/script/download.php#google_vignette
然后修改moviepy  config_default.py 里面的 imagemagick路径 ， 
IMAGEMAGICK_BINARY =r"D:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe"# os.getenv('IMAGEMAGICK_BINARY', 'auto-detect')

"""

from moviepy.editor import VideoClip, TextClip, CompositeVideoClip, AudioFileClip,ImageClip
from moviepy.video.tools.drawing import color_gradient
import re


# 解析LRC文件
def parse_lrc(lrc_file):
    timestamps = []
    lyrics = []
    with open(lrc_file, 'r', encoding='utf-8') as f:
        for line in f:
            match = re.search(r'\[(\d{2}):(\d{2})\.(\d{2,3})\](.+)', line)
            if match:
                minute, second, millisecond, text = match.groups()
                timestamp = int(minute) * 60 + int(second) + int(millisecond) / 1000.0
                timestamps.append(timestamp)
                lyrics.append(text.strip())
    return timestamps, lyrics


# 生成带字幕的视频
def generate_video_with_subtitles(mp3_file, lrc_file, output_video):
    # 解析LRC文件获取时间戳和歌词
    timestamps, lyrics = parse_lrc(lrc_file)
    font = r'C:\Windows\Fonts\BIZ-UDGothicR.ttc'
    font = r'BIZ-UDGothicR.ttc'
    font = r'meiryo.ttc'
    # 读取MP3文件
    audio = AudioFileClip(mp3_file)

    # 设置视频的背景色和字幕样式
    background_color = [0, 0, 0]  # 黑色背景
    font_color = 'black'  # [255, 255, 255]  # 白色字体
    font_size = 12  # 字体大小
    method = "label"  # 文本的对齐方式
    text_clips = []

    v1 = ImageClip('bg.png')
    v1 = v1.set_duration(audio.duration)
    # 创建每个歌词的TextClip
    for timestamp, lyric in zip(timestamps, lyrics):
        start_time = timestamp
        end_time = timestamps[timestamps.index(timestamp) + 1] if timestamps.index(timestamp) < len(
            timestamps) - 1 else audio.duration

        txt = TextClip(lyric,font=font ,  fontsize=font_size, color=font_color, method=method, kerning=5)
        txt = txt.set_start(start_time).set_end(end_time)
        txt = txt.set_position(('center', 'center')).set_duration(end_time - start_time)
        text_clips.append(txt)

        # 创建一个黑色背景的Clip
    # final_clip = VideoClip(make_frame=lambda t: color_gradient(t,(854,480), background_color, background_color),
    #                        duration=audio.duration)
    final_clip = v1
    final_clip = final_clip.set_audio(audio)
    v1 = v1.set_duration(audio.duration)


    # 将所有的TextClip合并到背景Clip上
    final_clip = CompositeVideoClip([final_clip] + text_clips)

    # 导出视频
    final_clip.write_videofile(output_video, codec='libx264',fps=24)


# 要使用的文件 mp3 lrc  
mp3_file = "新标准日本语初级下单词_25.mp3"
lrc_file = "新标准日本语初级下单词_25.lrc"
# 输出
output_video = "新标准日本语初级下单词_25.mp4"

# 调用函数生成带字幕的视频
generate_video_with_subtitles(mp3_file, lrc_file, output_video)

print(f"Video with subtitles has been generated at {output_video}")